﻿Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Partial Class Controls_AddNewCard
    Inherits System.Web.UI.UserControl
    Dim conn As SqlConnection
    Dim com As SqlCommand
    Dim reader As SqlDataReader

    Dim connectionString As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString

    Dim u As MembershipUser
    Dim personId As Int32

    Function CheckNewCardNumber() As Boolean

        ' Validation not working
        'Return True

        Dim validation As Boolean
        Dim cardnum = txtNewCardNumber.Text
        'txtCardType1.Text = cardnum
        'cboCCType
        Dim selected = cboCCNewType.SelectedValue.ToString()
        If cardnum.Length > 0 Then
            If cardnum.Length > 4 Then
                Dim trimedtext As String = cardnum.Replace(" ", "")
                Dim trimedtext1 As String = trimedtext.Substring(0, 1)
                Dim trimedtext2 As String = trimedtext.Substring(0, 2)
                Dim trimedtext3 As String = trimedtext.Substring(0, 3)
                Dim trimedtext4 As String = trimedtext.Substring(0, 4)
                If selected = "1" Then
                    If CDbl(trimedtext1) = 4 Then
                        If trimedtext.Length = 13 OrElse trimedtext.Length = 16 Then
                            MsgEditLbl.Text += ("Visa is ok")

                            validation = True
                        Else
                            MsgEditLbl.Text += ("Visa is NOT ok")
                            validation = False
                        End If
                    Else
                        MsgEditLbl.Text += ("Visa number is NOT ok")
                    End If


                End If
                If selected = "2" Then
                    If CDbl(trimedtext2) = 36 OrElse CDbl(trimedtext2) = 51 OrElse CDbl(trimedtext2) = 52 OrElse CDbl(trimedtext2) = 53 OrElse CDbl(trimedtext2) = 54 OrElse CDbl(trimedtext2) = 55 Then
                        If trimedtext.Length = 14 OrElse trimedtext.Length = 16 Then
                            MsgEditLbl.Text = ("Mastercard is ok")
                            validation = True
                        Else
                            MsgEditLbl.Text = ("Mastercard is NOT ok")
                            validation = False
                        End If
                    Else
                        MsgEditLbl.Text = ("Mastercard number is NOT ok")
                    End If

                End If

            End If
        Else
            MsgEditLbl.Text = "Please enter valid cart number it must be more then 4 digits."
            validation = False
        End If
        Return validation
    End Function
    Function CheckNewCVVNumber() As Boolean
        Dim validation As Boolean
        Dim number As Integer
        Dim CVVnum As Boolean = Int32.TryParse(txtNewCVV.Text.Replace("_", "").Replace(" ", ""), number)
        If CVVnum Then
            If txtNewCVV.Text.Replace(" ", "").Length = 4 Then

                If CVVnum Then
                    MsgEditLbl.Text += ("CVV has three numbers")
                    validation = True
                End If
            Else
                MsgEditLbl.Text += ("CVV must not be longer then three numbers")
                validation = False
            End If
        Else
            MsgEditLbl.Text += ("CVV has to be number")
            validation = False
        End If
        Return validation
    End Function
    Function CheckNewExpDate() As Boolean
        Dim validation As Boolean
        If cboCardExpiryNewMM.SelectedItem IsNot Nothing AndAlso cboCardExpiryNewYY.SelectedItem IsNot Nothing Then
            Dim selectedmonth = cboCardExpiryNewMM.SelectedItem.ToString()
            Dim selectedyear = cboCardExpiryNewYY.SelectedItem.ToString()

            Dim currentmonth = Date.Today.Month
            Dim currentyear = Date.Today.Year

            If (currentyear - 2000).ToString() = selectedyear Then
                If currentmonth > CInt(selectedmonth) Then
                    MsgEditLbl.Text += ("Cart expired")
                    validation = False
                Else
                    validation = True
                End If
            ElseIf Not (currentyear - 2000).ToString() > selectedyear Then
                validation = True
            Else
                MsgEditLbl.Text += ("Cart Edit expired")
                validation = False
            End If

        Else

        End If

        Return validation

    End Function
    Function CheckNewValidDate() As Boolean
        Dim validation As Boolean
        If cboCardValidNewMM.SelectedItem IsNot Nothing AndAlso cboCardValidNewYY.SelectedItem IsNot Nothing Then
            Dim selectedmonth = cboCardValidNewMM.SelectedItem.ToString()
            Dim selectedyear = cboCardValidNewYY.SelectedItem.ToString()

            Dim validdate As DateTime = CDate("01" + "/" + selectedmonth + "/" + selectedyear)



            'Dim currentmonth = Date.Today.Month
            'Dim currentyear = Date.Today.Year

            'If (currentyear - 2000).ToString() = selectedyear Then
            '    If currentmonth > CInt(selectedmonth) Then
            '        MsgEditLbl.Text += ("Cart expired")
            '        validation = False
            '    Else
            '        validation = True
            '    End If
            'ElseIf Not (currentyear - 2000).ToString() > selectedyear Then
            '    validation = True
            'Else
            '    MsgEditLbl.Text += ("Cart Edit expired")
            '    validation = False
            'End If

        Else

        End If

        Return validation

    End Function


    Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        If CheckNewCardNumber() AndAlso CheckNewExpDate() AndAlso CheckNewCVVNumber() Then
            AddNewCard()
            Response.Redirect("~/private/secure_members/payment/ConfirmOrder.aspx")
        End If

    End Sub
    Function CheckDuplicates(EntityId As Integer, CardNumber As String) As Integer

        conn = New SqlConnection(connectionString)
        com = New SqlCommand()
        Dim parmOUT As New SqlParameter("@bExists", SqlDbType.SmallInt)
        parmOUT.Direction = ParameterDirection.Output

        com.Connection = conn

        com.CommandType = CommandType.StoredProcedure

        com.CommandText = "pay.usp_CardDetails_Exist"

        com.Parameters.Add("@EntityId", Data.SqlDbType.Int).Value = EntityId
        com.Parameters.Add("@CardNumber", Data.SqlDbType.NVarChar).Value = CardNumber.Replace("""", "")
        com.Parameters.Add(parmOUT)

        conn.Open()
        com.ExecuteNonQuery()
        conn.Close()

        Return CInt(com.Parameters("@bExists").Value)
    End Function
    Sub AddNewCard()
        'Dim y As Object
        u = Membership.GetUser(HttpContext.Current.User.Identity.Name)

        Dim getpersonid As New GetPersonIdFromUserId()

        personId = getpersonid.GetPersonId(CType(u.ProviderUserKey, Guid))

        Dim persondetailsTA As New LogginsLogDSTableAdapters.PersonTableAdapter()
        Dim persondetailsDT As LogginsLogDS.PersonDataTable
        persondetailsDT = persondetailsTA.GetData(CType(u.ProviderUserKey, Guid))
        Dim person = (From p In persondetailsDT.AsEnumerable() Select p).FirstOrDefault()

        Dim subStringl4d As String = Right(txtNewCardNumber.Text, 4)

        If CheckNewCardNumber() AndAlso CheckNewExpDate() AndAlso CheckNewCVVNumber() Then
            Dim payrequestTA As New LogginsLogDSTableAdapters.usp_PayRequestTableAdapter()
            Dim buycredits_startTA As New LogginsLogDSTableAdapters.SPTableAdapter()
            Dim usp_BuyCredits_CompleteTA As New LogginsLogDSTableAdapters.usp_BuyCredits_CompleteTableAdapter()
            Dim usp_BuyCredits_ErrorTA As New LogginsLogDSTableAdapters.SPTableAdapter()
            Dim carddetailsinsertTA As New LogginsLogDSTableAdapters.SPTableAdapter()

            If Not Session("SelectedEntityID") Is Nothing Then


                Dim table As DataTable = CType(Session("VirtualProductsDT"), DataTable)
                For Each dRow As DataRow In table.Rows


                    Dim x As Integer
                    Dim selectedentity As Integer = CInt(Session("SelectedEntityID").ToString().Replace("""", ""))
                    Dim carddetailsTA As New LogginsLogDSTableAdapters.usp_CardDetailsSelectTableAdapter()
                    Dim carddetailsDT As LogginsLogDS.usp_CardDetailsSelectDataTable

                    carddetailsDT = carddetailsTA.GetData(Nothing)
                    Dim findduplicates = From q In carddetailsDT.AsEnumerable() Where q.CardNumber = txtNewCardNumber.Text.Replace(" ", "").Replace("""", "") AndAlso q.EntityId = selectedentity Select q

                    Dim xx As Integer = findduplicates.Count


                    If findduplicates.ToList().Count <> 0 Then
                        Dim activecardsTA As New LogginsLogDSTableAdapters.usp_CardDetailsSelectByEntityId_DDLTableAdapter()
                        Dim activecardsDT As LogginsLogDS.usp_CardDetailsSelectByEntityId_DDLDataTable

                        activecardsDT = activecardsTA.GetData(selectedentity)
                        Dim activecards = (From q In activecardsDT.AsEnumerable() Select q).FirstOrDefault()
                        x = activecards.Id
                    Else
                        x = CInt(carddetailsinsertTA.usp_CardDetailsInsert(CInt(Session("SelectedEntityID")), person.FirstName, person.LastName, txtNewCardNumber.Text.Replace(" ", "").Replace("""", ""), subStringl4d, txtNewCVV.Text, CType(cboCCNewType.SelectedValue, Integer?), CType(cboCardExpiryNewMM.SelectedValue, Integer?), CType(cboCardExpiryNewYY.SelectedValue, Integer?), CType(cboCardValidNewMM.SelectedValue, Integer?), CType(cboCardValidNewYY.SelectedValue, Integer?), Date.Now, CType(1, Boolean?)))
                        Dim cd = CheckDuplicates(CInt(Session("SelectedEntityID")), txtNewCardNumber.Text.Replace(" ", "").Replace("""", ""))
                        Session("JustInsertedCard") = x
                    End If


                    'y = buycredits_startTA.usp_BuyCredits_Start(personId, CInt(Session("SelectedEntityID")), CType(cboCCNewType.SelectedValue, Byte?), 1, 1, CInt(dRow("ItemId")), CType(ddNewCurrency.SelectedValue, Integer?), CType(0.0, Decimal?), "Pending", CType(x, Integer?))


                Next
            End If

            'usp_BuyCredits_CompleteTA.GetData(CInt(Session("SelectedEntityID")), (CType(y, Integer?)), responseID)
            '
            Dim strMailFrom As String = ConfigurationManager.AppSettings("smtpmailfrom").ToString()
            Dim strMailTo As String = ConfigurationManager.AppSettings("accountapprovalemail").ToString()
            Dim sendemail As New SendEmailViaGoogle()

            Dim strMessage As String = "Your Credit Card is set up successfully."
            Dim strSubject As String = "Card registered"


            Try

                sendemail.SendEmail(strMailFrom, strMailTo, strSubject, strMessage)
                'Session("BuyDT") = Nothing
            Catch ex As Exception
                Throw ex
            End Try
            Response.Redirect("~/private/secure_members/payment/ConfirmOrder.aspx")


        End If

    End Sub

    Sub FillYearsExpiry()
        Dim year = CInt(Date.Now.Year) - 2000
        Dim yearsDT As DataTable = GetYearsTable()
        For index = 0 To 5
            yearsDT.Rows.Add(year + index)
        Next
        cboCardExpiryNewYY.DataSource = yearsDT
        cboCardExpiryNewYY.DataTextField = "Year"
        cboCardExpiryNewYY.DataValueField = "Year"
        cboCardExpiryNewYY.DataBind()
    End Sub

    Sub FillYearsValidy()
        Dim year = CInt(Date.Now.Year) - 2004
        Dim yearsDT As DataTable = GetYearsTable()
        For index = 0 To 4
            yearsDT.Rows.Add(year + index)
        Next
        cboCardValidNewYY.DataSource = yearsDT
        cboCardValidNewYY.DataTextField = "Year"
        cboCardValidNewYY.DataValueField = "Year"
        cboCardValidNewYY.DataBind()
    End Sub

    Function GetYearsTable() As DataTable
        ' Create new DataTable instance.
        Dim table As New DataTable
        ' Create four typed columns in the DataTable.
        table.Columns.Add("Year", GetType(Integer))

        Return table
    End Function

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            FillYearsExpiry()
            FillYearsValidy()
            'Label1.Text = Path.GetFileName(Request.Url.LocalPath) + "<br/>"
            'Label1.Text += Path.GetFileName(Request.Url.AbsolutePath) + "<br/>"
            'Label1.Text += Path.GetFileName(Request.UrlReferrer.OriginalString) + "<br/>"
            'Label1.Text += Path.GetFileName(Request.RawUrl) + "<br/>"
        End If

    End Sub

    Protected Sub ObjectDataSource2_Selecting(sender As Object, e As ObjectDataSourceSelectingEventArgs) Handles ObjectDataSource2.Selecting
        e.InputParameters("Id") = Nothing
    End Sub

    Protected Sub ODSCurrency_Selecting(sender As Object, e As ObjectDataSourceSelectingEventArgs) Handles ODSCurrency.Selecting
        e.InputParameters("Id") = Nothing

    End Sub

    'Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    '    Response.Redirect("~/private/secure_members/payment/BuyCredit.aspx")

    'End Sub

    Protected Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        Dim currentpage As String = Path.GetFileName(Request.Url.LocalPath)
        If currentpage = "MyCardDetails.aspx" Then
            Response.Redirect("~/private/secure_members/manage/MyCardDetails.aspx")
        Else
            Response.Redirect("~/private/secure_members/payment/" + currentpage)

        End If

    End Sub
End Class
